﻿using System.Collections.Generic;
using UnityEngine;

public class ObjectsPool<T> where T : PoolObject, new()
{
    public delegate void InitPoolObjectDelegate(T poolObject);
    /// <summary>
    /// 初始化委托
    /// </summary>
    private InitPoolObjectDelegate _initPoolObjectDelegate;
    /// <summary>
    /// 对象池
    /// </summary>
    private readonly Stack<T> _pool = new Stack<T>();

    /// <summary>
    /// 当前正在使用的列表
    /// </summary>
    public readonly List<T> CurUseList = new List<T>();

    /// <summary>
    /// 添加初始化事件
    /// </summary>
    /// <param name="data"></param>
    public void AddDelegate(InitPoolObjectDelegate data)
    {
        _initPoolObjectDelegate = data;
    }

    /// <summary>
    /// 创建对象
    /// </summary>
    /// <returns></returns>
    private T CreateObjects()
    {
        T poolObject = new T();
        _initPoolObjectDelegate?.Invoke(poolObject);
        return poolObject;
    }

    /// <summary>
    /// 通过对象池获取对象
    /// </summary>
    public T GetObjectFromPool()
    {
        T poolObject = null;
        if (_pool.Count > 0)
        {
            poolObject = _pool.Pop();
        }
        else
        {
            poolObject = CreateObjects();
        }

        return poolObject;
    }

    /// <summary>
    /// 回收对象
    /// </summary>
    public virtual void Recycle(T poolObject)
    {
        _pool.Push(poolObject);
        CurUseList.Remove(poolObject);
    }
}

public class PoolObject : BaseManager<PoolObject>
{
    public virtual void Init()
    {

    }
    /// <summary>
    /// 游戏对象
    /// </summary>
    public GameObject GObj;

    public PoolObject()
    {
        GObj = new GameObject();
    }

    /// <summary>
    /// 回收对象
    /// </summary>
    public virtual void Recycle()
    {
    }

    /// <summary>
    /// 帧刷新
    /// </summary>
    public virtual void Update()
    {
    }

    public virtual void InitData()
    {
    }
}


public class SpriteObject : PoolObject
{
    public SpriteRenderer SR;
    public SpriteObject()
    {
        GameObject child = new GameObject();
        SR = child.AddComponent<SpriteRenderer>();
        child.transform.SetParent(GObj.transform);
    }

    public override void InitData()
    {
        base.InitData();
        SetSprite();
    }

    public void SetSprite()
    {
        SR.sprite = Resources.Load<Sprite>("Sprites/miao");
    }
}